package com.century.sjt.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.R;
import com.century.sjt.util.Check;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.TitleBar.SjtTitleBar;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.Map;

/**
 * @author:周玲波
 * @Description: 录入商家订单信息
 * @date : 2016/9/3 21:40
 */
public class MyOrderEnteringMessage extends BaseActivity{

    private SjtTitleBar titleBar;
    private EditText KD_OrderNumber;//快递单号
    private TextView tv_Kd;//快递公司名称
    private TextView tvOrder;//订单号
    private String OrderId;
    private String type;
    private Button btn_submit;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_commodity_information);

        OrderId = getIntent().getStringExtra("orderId");
        type = getIntent().getStringExtra("type");
        if ("inputOrder".equals(type)){
            //跳转到扫描二维码
            Intent intent = new Intent();
            intent.setClass(MyOrderEnteringMessage.this, QRRecordCodeScanActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivityForResult(intent, Constant.SCANNIN_GREQUEST_CODE);
        }
        initView();
        initEvent();
        initData();

    }

    @Override
    protected void initView() {
        titleBar = (SjtTitleBar) findViewById(R.id.title_bar);
        tv_Kd = (TextView) findViewById(R.id.text_kuaidi);
        tvOrder = (TextView) findViewById(R.id.text_order_number);
        btn_submit = (Button) findViewById(R.id.btn_submit);
        KD_OrderNumber= (EditText) findViewById(R.id.edit_order_number);
    }

    @Override
    protected void initEvent() {
        titleBar.setTitle(getResources().getString(R.string.tab_input_order));
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        titleBar.setRightIconResourc(getResources().getString(R.string.icon_scan_it));
        titleBar.setRightLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //跳转到扫描二维码
                Intent intent = new Intent();
                intent.setClass(MyOrderEnteringMessage.this, QRRecordCodeScanActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivityForResult(intent, Constant.SCANNIN_GREQUEST_CODE);
            }
        });
        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if ("".equals(KD_OrderNumber.getText().toString())||null==KD_OrderNumber.getText().toString()){
                    TipUtil.showToast(getResources().getString(R.string.error_order_is_no), MyOrderEnteringMessage.this, 1);
                }else {
                    sendGood();//提交接口
                }
            }
        });
    }

    @Override
    protected void initData() {
        tvOrder.setText(OrderId);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //扫描二维码返回的信息(录入订单)
        qrRecordCodeResult(requestCode, resultCode, data);

    }

    /**
     * 录入订单 扫描条形码返回结果
     */
    public void qrRecordCodeResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case com.century.sjt.util.Constant.SCANNIN_GREQUEST_CODE:
                if (resultCode == Activity.RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    final String shippingNumber = bundle.getString("result");
                    if(Check.isOrderNumber(shippingNumber)) {
                        //录入订单dialog
                       KD_OrderNumber.setText(shippingNumber);
                    }else {
                        TipUtil.showToast(getResources().getString(R.string.error_order_is_wrong), MyOrderEnteringMessage.this, 1);
                    }
                }
                break;

        }
    }


    /**
     * 创建物流信息
     *
     */
    private void sendGood() {
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME,getResources().getString(R.string.error_please_waitting), MyOrderEnteringMessage.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.sendGood, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    TipUtil.log("接口返回", res.toString(), 1);
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        Intent intent = new Intent(MyOrderEnteringMessage.this, MyOrderDetailsActivity.class);
                        intent.putExtra("orderId", OrderId);
                        intent.putExtra("falg",3);
                        startActivity(intent);
                    } else {//失败
                        TipUtil.showToast(message, MyOrderEnteringMessage.this, 1);
                    }
                } catch (Exception ex) {
                    TipUtil.closeProgressDialog();
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service),MyOrderEnteringMessage.this, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), MyOrderEnteringMessage.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("orderId",OrderId);
                map.put("shippingCompanyCode","SF");
                map.put("shippingNumber",KD_OrderNumber.getText().toString().trim());
                return map;
            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(com.century.sjt.util.Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);
    }

}
